package com.leyou.auth.interceptors;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.thread.UserContext;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 虎哥
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private final JwtUtils jwtUtils;

    public UserInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取cookie中jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        // 2.校验并解析jwt
        Payload payload = jwtUtils.parseJwt(jwt);
        // 3.获取用户信息
        UserDetails user = payload.getUserDetail();
        log.info("用户{}正在访问{}!", user.getUsername(), request.getRequestURI());
        // 4.保存用户
        UserContext.setJwt(jwt);
        UserContext.setUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在代码结束时，移除用户信息
        UserContext.removeUser();
    }
}
